export const createStandardHttpPath = (...args: string[]) => {
  let ret: string = ""
  args = args.filter(i => i)
  args.forEach(i => {
    ret += i.startsWith("/") ? i: `/${i}`
  })
  return ret
}

export const formatRequestPathWithQueryString = (path: string) => {
  let params = {}
  const arr = path.split("?")
  const queryString = arr[1]
  if(queryString){ // name=1&name=2&age=15
    queryString.split("&").forEach(item => {
      const [key, val] = item.split("=")
      params[key] = val
    })
  }
  return [arr[0], params]
}


export function parseRequestMappingPattern(path: string) {
  const re = /^\{.+\}$/
  const pattern = []
  const pathArr = path.split("/").slice(1)
  pathArr.forEach(item => {
    const ret = re.exec(item)
    if(ret) {
      pattern.push({
        exact: false,
        param: item.slice(1, -1)
      })
    } else {
      pattern.push({
        exact: true,
        pattern: item
      })
    }
  })
  return pattern
}

export function requestPatternMatch(url: string, pattern, params = {}): [flag: boolean, params: {}] {
  const urlArr = url.split("/").slice(1)
  if(urlArr.length !== pattern.length) return [false, params]
  for (let i = 0; i < urlArr.length; i++) {
    const patternSlice = pattern[i]
    const urlSlice = urlArr[i]
    if(patternSlice.exact){
      if(patternSlice.pattern !== urlArr[i]) return [false, params]
    }else {
      params[patternSlice.param] = urlSlice
    }
  }
  return [true, params]
}
